<?
if($config_page) {
	foreach($config_page as $key => $item) {
		if($item['editable']) {
			foreach($item['editable'] as $key2 => $item2) {
				if($item2['title']) {
					$config_page[$key]['editable'][$key2]['title'] = $item2['title'];
				} else {
					foreach($item['listtitles'] as $item3) {
						if($item3['zd'] == $key2 || $item3['zdr'] == $key2) {
							$config_page[$key]['editable'][$key2]['title'] = $item3['title'];
							break;
						}
					}
				}
			}
		}
		if($item['search_items']) {
			foreach($item['search_items'] as $key2 => $item2) {
				if(!$item2['key']) {
					$config_page[$key]['search_items'][$key2]['key'] = "k".substr(md5($item2['title'].$item2['zd']), 0, 8);
				}
			}
		}
	}
}

if($act == 'login') {
	if($config_nologin) {
		gredirect("?");
		exit;
	}
	if($config_login_func) {
		$config_login_func();
		exit;
	}
	if(r('m') == 'dologin') {
		$username = p('username');
		$password = p('password');
		$yzm = p('yzm');
		if($username == '' || $password == '') exit;

		if($config_host) {
			if(is_string($config_host)) $config_host = array($config_host);
			$ref = $_SERVER['HTTP_REFERER'];
			$suc = false;
			foreach($config_host as $host1) {
				if(stripos($ref, "http://{$host1}/") === 0 || stripos($ref, "https://{$host1}/") === 0) {
					$suc = true;
					break;
				}
			}
			if(!$suc) exit;
		}

		$table = 'admin';
		if(!$zd_un) $zd_un = 'un';
		if(!$zd_pw) $zd_pw = 'pw';
		if($config_admin_table) $table = $config_admin_table;
		if($config_admin_table_un) $zd_un = $config_admin_table_un;
		if($config_admin_table_pw) $zd_pw = $config_admin_table_pw;
		$sqlext = '';
		if($zd_un2) {
			$sqlext .= " or {$zd_un2}='{$username}'";
		}
		if($zd_un3) {
			$sqlext .= " or {$zd_un3}='{$username}'";
		}
		if($zd_un4) {
			$sqlext .= " or {$zd_un4}='{$username}'";
		}
		$sql = "select * from {$table} where {$zd_un}='{$username}' {$sqlext}";
		$row = fetchOne($sql);
		if($row && $row['enable'] != 1) {
			echoRs(0, '此用户已被停用！');
		}
		if($row && $row['err'] >= 5) {
			echoRs(0, '此用户已被锁定，请联系管理员解锁！');
		}
		
		if(!$row) {
			if($config_sendyzm_nocheckunexists) {
				$row = array('un' => $username, 'password' => $password);
			} else {
				echoRs(0, '用户名或密码错误！');
			}
			
		}
		if(!$config_sendyzm_func || !$config_sendyzm_nocheckpassword) {
			if($row[$zd_pw] == '' || $row[$zd_pw] != $password) {
				query("update {$table} set err=err+1 where id=".$row['id']);
				echoRs(0, '用户名或密码错误！');
			}
		}
		if($row) {
			if($config_sendyzm_func) {
				if($yzm) {
					$r = $config_checkyzm_func($row, $yzm);
					if($r) {
						if(!$row['id'] && $config_sendyzm_nocheckunexists) {
							$row = fetchOne($sql);
						}
						$token = user_login($row['id'], $table);
						echoRs(1, 'ok', array('token' => $token));
					} else {
						echoRs(0, '验证码错误！');
					}
				} else {
					$r = $config_sendyzm_func($row);
					if($r) {
						echoRs(1, 'ok');
					} else {
						echoRs(0, '短信验证码发送失败！');
					}
				}
			} else {
				$token = user_login($row['id'], $table);
				echoRs(1, 'ok', array('token' => $token));
			}
			
		} else {
			echoRs(0, '用户名或密码错误！');
		}
		exit;
	}
	
	$tpl_name = "login".($isphone?"_m":"").".tpl.php";
	if($config_tpl_dir && is_file($config_tpl_dir."/".$tpl_name)) {
		include($config_tpl_dir."/".$tpl_name);
		exit;
	}
	if($isie) {
		include ADMIN_INC_ROOT."/tpl/".$tpl_name;
	} else {
		include ADMIN_INC_ROOT."/tpl/login_new.tpl.php";
	}

	exit;
}
if($act == 'logout') {
	if($config_nologin) {
		gredirect("?");
		exit;
	}
	gredirect("?act=login");
	exit;
}
if($act == 'repass') {
	admininc_check_token();
	if(r('m') == 'submit') {
		$oldpw = $_POST['oldpw'];
		$newpw = $_POST['newpw'];
		if($oldpw == '' || $newpw == '') exit;
		if($oldpw != $adminInfo['pw']) {
			echoRs(0, '原密码不正确！');
		}
		if(is_jdpw($newpw)) {
			echoRs(0, '新密码强度不够！不能纯数字，长度至少6位！不能包含123456等。');
		}
		$table = 'admin';
		if($config_admin_table) $table = $config_admin_table;
		query("update {$table} set pw = '{$newpw}' where id=".$adminid);
		echoRs(1, '修改密码成功！');
		exit;
	}
	ob_start();
	$tpl_name = "repass.tpl.php";
	if($config_tpl_dir && is_file($config_tpl_dir."/".$tpl_name)) include($config_tpl_dir."/".$tpl_name);
	else include ADMIN_INC_ROOT."/tpl/".$tpl_name;
	
	$html = ob_get_clean();
	
	$data = array('html' => $html);
	echoRs(1, 'ok', $data);

	exit;
}
if($act == 'getMenus') {
	admininc_check_token();

	$menus_html = '';
	if(!$isphone) {
		
		$firstMenu = $config_menulist[0];
		$firstMenuN = 0;
		foreach($config_menulist as $key => $item) { 
			if($item['first']) {
				$firstMenu = $item;
				$firstMenuN = $key;
			}
		
			$menus_html .= '<a id="menua_'.$key.'" class="menuitem" href="javascript:;" onclick="setNowMenu('.$key.');open_showtype('.htmlspecialchars(json_encode($item)).')">'.$item['title'].'</a>';
		}
		if(!$config_noauth && !$config_nologout) $menus_html .= '<a class="menuitem" href="javascript:;" onclick="doLogout()" style="color:red">退出登录</a>';

	
		$top_html = '<table cellpadding="0" cellspacing="0" border="0" width="100%"><tr><td style="color:white; font-size:30px;padding-left:20px; font-family:黑体; font-weight:600;text-shadow: 1px 1px 1px rgba(255, 255, 255, 0.1),-1px -1px 1px rgba(255, 255, 255, 0.1);" height="55" valign="middle" align="left">';
		if($top_left_html) $top_html .= $top_left_html; else $top_html .= $config_title;
		$top_html .= '</td><td align="right" style="color:white; padding-right:10px; font-size:14px">';
		
		if($top_right_html) $top_html .= $top_right_html; 
		else if($adminInfo['name']) $top_html .= '登录人: '.$adminInfo['name'];
		$top_html .= '</td></tr></table>';
	} else {
		$totalwidth = 0;
		$resize = 11;
		foreach($config_menulist as $item) { 
			$slen = strlen($item['title']);
			$totalwidth += $slen*$resize + 10;
		}
		$totalwidth += 8*$resize+10;
		
		$firstMenu = $config_menulist[0];
		$firstMenuN = 0;
		foreach($config_menulist as $key => $item) { 
			if($item['first']) {
				$firstMenu = $item;
				$firstMenuN = $key;
			}
			$slen = strlen($item['title']);
			$width = $slen*$resize;
			
			$menus_html .= '<a id="menua_'.$key.'" class="button'.($key==0?"2":"1").'" href="javascript:;" onclick="setNowMenu('.$key.');open_showtype('.htmlspecialchars(json_encode($item)).')"><nobr>'.$item['title'].'</nobr></a>';
		}
		$top_html = '<table cellpadding="0" cellspacing="0" border="0" width="100%"><tr><td style="color:white; font-size:20px;padding-left:10px; font-family:黑体" height="'.$config_top_height.'" valign="middle" align="left">';
		if($top_left_html) $top_html .= $top_left_html; else $top_html .= $config_title;

		$top_html .= '</td><td align="right" style="color:white; padding-right:10px; font-size:14px">';
		if($top_right_html) $top_html .= $top_right_html; 
		else if($adminInfo['name']) {
			$top_html .= '登录人: '.$adminInfo['name'];
			if(!$config_noauth && !$config_nologout) $top_html .= ' <a style="color:white;text-decoration:none;margin-left:5px" href="javascript:;" onclick="doLogout()">退出</a>';
		}
		
		$top_html .= '</td></tr></table>';
	}
	$adminInfo2 = $adminInfo;
	$zd_pw = 'pw';
	if($config_admin_table_pw) $zd_pw = $config_admin_table_pw;
	unset($adminInfo2[$zd_pw]);
	unset($adminInfo2['err']);unset($adminInfo2['enable']);unset($adminInfo2['token']);unset($adminInfo2['token_expire']);unset($adminInfo2['last_login']);unset($adminInfo2['addtime']);


	$table = 'admin';
	if($config_admin_table) $table = $config_admin_table;

	$token_expire = date('Y-m-d H:i:s', time()+86400*7);
	if(!$config_nodb) query("update {$table} set token_expire='{$token_expire}' where id=".$adminid);


	echoRs(1, 'ok', array('menus_html' => $menus_html, 'top_html' => $top_html, 'first_showtype' => $firstMenu, 'firstMenuN' => $firstMenuN, 'title' => strip_tags($config_title), 'adminInfo' => $adminInfo2, 'config_hide_frame_left' => intval($config_hide_frame_left)));
}

if($act == 'uploadpic') {
	admininc_check_token();
	$name = trim(r('name'));
	$formname = trim(r('formname'));
	$up_showtype = trim(r('up_showtype'));
	$picdata = trim(p('picdata'));
	$upload_type = trim(p('upload_type'));

	$upload_type = unserialize(aes_decrypt($upload_type, get_up_key()));
	$edit = $upload_type['edit'];
	$config = $upload_type['config'];

	if(!$edit || !$config) exit;
	
	$umeditor = trim(g('umeditor'));
	if($umeditor != '1' && (!$formname || !$name)) {
		exit;
	}
	if($picdata) {
		$type = 2;
		$fInfo = $picdata;
	} else {
		$type = 1;
		$fInfo = 'file';
	}
	$upload_dir = 'upload/';
	$upload_prefix = '';
	
	if($config['upload_dir']) $upload_dir = $config['upload_dir'];
	if($config['upload_prefix']) $upload_prefix = $config['upload_prefix'];
	$multiple = $edit['multiple'];
	$multiple_split = $edit['multiple_split'];
	$after_upload = $edit['after_upload'];
	$allowExts = $edit['allowExts'];

	$path = saveUploadFile($type, $fInfo, $upload_dir, $allowExts);
	if($upload_prefix) {
		$path = replace_first($upload_prefix, '', $path);
	}
	if($multiple == '1') {
		if(!$multiple_split) $multiple_split = '#';
	}
	if($path) {
		if($umeditor == '1') {
			echo json_encode(array(
				"originalName" => $name ,
				"name" => $name,
				"url" => $path,
				"size" => 0 ,
				"type" => '.jpg',
				"state" => 'SUCCESS'
			));
		} else {
			echo '<script>window.parent.uploadFinish("'.$path.'", "'.$name.'", "'.$formname.'", "'.$multiple.'", "'.$multiple_split.'", "'.$after_upload.'", "'.$upload_prefix.'");</script>';
		}
	} else {
		echo '<script>window.parent.uploadFinish("#fail", "'.$name.'", "'.$formname.'");</script>';
	}

	exit;
}


if($act == 'list_frame') {
	admininc_check_token();
	$showtype = r('showtype');
	$config = $config_page[$showtype];
	if(!$config) exit;

	ob_start();

	$extraJs = '';
	$tpl_name = "list_frame.tpl.php";
	if($config_tpl_dir && is_file($config_tpl_dir."/".$tpl_name)) include($config_tpl_dir."/".$tpl_name);
	else include ADMIN_INC_ROOT."/tpl/".$tpl_name;

	$html = ob_get_clean();
	
	if($config['addjs']) { 
		foreach($config['addjs'] as $js) {
			if(substr($js, 0, 1) == '#') {
				$extraJs .= substr($js, 1)."\r\n";
			} else if(substr($js, 0, 1) == '$') {
				ob_start();
				include(substr($js, 1));
				$extraJs .= ob_get_clean();
			} else {
				ob_start();
				include("js/{$js}");
				$extraJs .= ob_get_clean();
			}
		} 
	}

	if($config['onloadjs']) $extraJs .= $config['onloadjs'];

	$data = array('html' => $html, 'search_items' => $config['search_items'], 'editheight' => intval($config['editheight']), 'editparam' => $config['editparam'], 'extraJs' => $extraJs, 'show_loading' => trim($config['show_loading']));
	echoRs(1, 'ok', $data);

	exit;
}
if($act == 'list') {
	admininc_check_token();
	$showtype = r('showtype');
	$config = $config_page[$showtype];
	
	if(!$config) exit;

	if($config['relative_width']) {
		foreach($config['listtitles'] as $n => $item) {
			$config['listtitles'][$n]['width'] = relative_width($item['width']);
		}
	}


	$listtitles = $config['listtitles'];
	
	if($config['listsql']) $sql = $config['listsql'];
	else {
		$sql = "select * from ".$config['table'];
		if($config['delmode'] == 1) $sql .= " where isdel=0";
	}

	$islistdata = false;
	if(isset($config['data_func'])) {
		$islistdata = true;
	}
	
	if($config['search_items'] && !$islistdata) {
		$esql = '';
		
		foreach($config['search_items'] as $item) {
			$key = $item['key'];
			$zd = $item['zd'];
			$mode = $item['mode'];
			$notauto = $item['notauto'];
			$type = $item['type'];
			$dbenc = $item['dbenc'];
			if($notauto) continue;
			if(!isset($_POST['search_'.$key])) {
				if($type == 'select') {
					$a = array_keys($item['select']);
					$_POST['search_'.$key] = $a[0];
				} else {
					continue;
				}
			}
			$s = trim($_POST['search_'.$key]);
			if($s == '' || $s == '_all') continue;

			$es = '';
			$a1 = explode(",", $zd);
			foreach($a1 as $zd1) {
				if($es != '') $es .= ' or ';
				if($mode == 'like') {
					$s = str_replace("%", "\\%", $s);
					$s = str_replace("_", "\\_", $s);
					$es .= " {$zd1} like '%{$s}%' ";
				}
				else if($mode == '>') $es .= " {$zd1} > '{$s}' ";
				else if($mode == '>=') $es .= " {$zd1} >= '{$s}' ";
				else if($mode == '<') $es .= " {$zd1} < '{$s}' ";
				else if($mode == '<=') $es .= " {$zd1} <= '{$s}' ";
				else {
					if($dbenc) $es .= " ({$zd1} = '{$s}' or {$zd1} = '".dbenc($s)."') ";
					else $es .= " {$zd1} = '{$s}' ";
				}
			}

			if($esql != '') $esql .= " and ";
			$esql .= '('.$es.')';
		}
		
		if(strstr($esql, 'isdel')) {
			$sql = str_replace("isdel=0", "1", $sql);
		}
		if($esql) {
			if(preg_match("/^([\s\S]+)group[\r\n\t ]+by([\s\S]+)$/i", $sql, $m)) {
				$sql1 = $m[1];
				$sql2 = $m[2];
				if(preg_match("/[\r\n\t ]+where[\r\n\t ]+/i", $sql1)) {
					$sql1 .= " and " . $esql;
				} else {
					$sql1 .= " where " . $esql;
				}
				$sql = $sql1." group by ".$sql2;
			} else {
				if(preg_match("/[\r\n\t ]+where[\r\n\t ]+/i", $sql)) {
					$sql .= " and " . $esql;
				} else {
					$sql .= " where " . $esql;
				}
			}
		}
	}
	if($config['orderby']) $sql .= " order by ". $config['orderby'];


	if($config['info_m']) {
		foreach($config['info_m'] as $key => $func) {
			if(r('m') == $key) {
				$func();
				exit;
			}
		}
	}
	if(r('m') == 'export' && $config['exportname']) $isexport = 1;

	$page = max(1, intval(r('page')));
	$pagesize = max(10, intval($config['showpage']));

	if($islistdata) {
		$data_func = $config['data_func'];
		$data = $data_func($page, $pagesize, $pageinfo);
	} else {
		if($config['showpage'] && !$isexport) {
			if($config['nocount']) {
				$start = ($page-1)*$pagesize;
				$sql .= " limit {$start},{$pagesize}";
				$data = fetchAll($sql);
				
				$pageinfo = array();
				$pageinfo['pagecount'] = 999;
				$pageinfo['count'] = 9999;
				$pageinfo['page'] = $page;
				$pageinfo['pagesize'] = $pagesize;
			} else {
				$data = getByPage($sql, r('page'), $config['showpage'], $pageinfo);
			}
		} else {
			ini_set("memory_limit","1024M");
			$data = fetchAll($sql);
		}
	}
	if(!$data && $config['show_nodata']) {
		$data = array(
			array('msg' => '暂无数据'),	
		);

		$listtitles = array(
			array('zd' => 'msg', 'width'=>300, 'title' => '提示'),
		);
	}
	$data_deal_func = $config['data_deal_func'];
	$row_deal_func = $config['row_deal_func'];
	$can_edit_func = $config['can_edit_func'];
	if($data_deal_func) {
		$data = $data_deal_func($data);
	}
	$showListArr = array();
	foreach($data as $key => $item) {
		if($row_deal_func) {
			$item = $row_deal_func($item);
		}
		$lineArr = array();
		foreach($listtitles as $key => $titem) {
			if($titem['hidden']) continue;
			if($titem['showfor']) {
				if($titem['showfor'] == 'export' && !$isexport) continue;
				if($titem['showfor'] == 'page' && $isexport) continue;
			}
			if($titem['op']) {
				$html = '';
				$can_edit = true;
				if($can_edit_func) {
					if(!$can_edit_func(0, $item)) {
						$can_edit = false;
					}
				}
				if($can_edit) {
					if(!$titem['hideedit']) $html .= '<input class="button" type="button" value="编辑" style="cursor:pointer;height:25px" onclick="showInfo(\''.$item['id'].'\')" />';
					if($config['showdel']) {
						if($item['isdel'] == 0) $html .= '&nbsp;<input class="button" type="button" value="删除" style="cursor:pointer;background:#FF6666;height:25px" onclick="delIt('.$item['id'].')" />';
						else $html .= '&nbsp;<input class="button" type="button" value="恢复" style="cursor:pointer;background:#009900;height:25px" onclick="delIt('.$item['id'].', 1)" />';
					}
				}
				if($config['listbts']) { 
					foreach($config['listbts'] as $item2) {
						$bt = $item2($item);
						
						if($bt) {
							if($bt['edit']) {
								$bt['onclick'] = "showInfo('".$item['id']."')";
							}
							if($bt['bt_m']) {
								$bt['onclick'] = "doBt_m('{$showtype}', ".$item['id'].", '".$bt['bt_m']."', '".trim($bt['bt_m_tip'])."', '".trim($bt['bt_m_more'])."')";
							}
							if(!$bt['bgcolor']) $bt['bgcolor'] = $config_bgcolor;
							$html .= '&nbsp;<input class="button" type="button" value="'.$bt['title'].'" style="cursor:pointer;height:25px;background:'.$bt['bgcolor'].';'.$bt['style'].'" onclick="'.$bt['onclick'].'" '.$bt['more_attr'].' />';
						}
					}
				}
				$parr = array();
				$parr['op'] = 1;
				$parr['html'] = $html;
				if($titem['align']) $parr['align'] = $titem['align'];
				if($titem['style']) $parr['style'] = $titem['style'];
				$lineArr[] = $parr;
			} else {
				$lineArr[] = get_list_line_value($item, $titem);
			}
		}
		$showListArr[] = $lineArr;
	}
	//print_r($showListArr);
	if($isexport) {
		set_time_limit(300);
		
		require_once(ADMIN_INC_ROOT."/include/getxlsx.php");
		if(!is_dir("xls")) @mkdir("xls");
		$fn_o = md5(time()."_".rand()).".xlsx";
		$fn = "xls/".$fn_o;
		//ini_set("display_errors", "on");
		$list = array();
		foreach($showListArr as $key => $item) {
			$row = array();
			foreach($item as $v) { 
				if(!is_array($v)) $v = array('html' => $v);
				if(!$v['op']) $row[] = strip_tags($v['html']);
			}
			$list[] = $row;
		}
		$titles = array();
		$widths = array();
		foreach($listtitles as $item) { 
			if($item['hidden']) continue;
			if($item['showfor']) {
				if($item['showfor'] == 'export' && !$isexport) continue;
				if($item['showfor'] == 'page' && $isexport) continue;
			}
			if($item['op']) continue;
			$titles[] = $item['title'];
			$widths[] = intval($item['width']/6);
		}
		
		$sheet_name = 'Sheet1';
		if($config['export_sheetname']) {
			$sheet_name = $config['export_sheetname'];
		}

		$sheets = array(array(
			'titles' => $titles,
			'widths' => $widths,
			'list' => $list,
			'sheet_name' => $sheet_name,
		));
		getXlsx($sheets, $fn, false);

		$exportname = $config['exportname'];
		
		echoRs(1, 'ok', array('url' => "?act=downxlsx&fn=".urlencode($fn_o)."&exportname=".urlencode($exportname)));
	} else {
		ob_start();

		$totalwidth = 0;
		foreach($listtitles as $item) {
			if($item['hidden']) continue;
			if($item['showfor']) {
				if($item['showfor'] == 'export' && !$isexport) continue;
				if($item['showfor'] == 'page' && $isexport) continue;
			}
			$totalwidth += $item['width'];
		}

		$titles = array();
		$title_widths = array();
		$title_widths_pos = 0;
		$title_widths_nowsize = 0;
		foreach($listtitles as $key => $item) {
			if($item['hidden']) continue;
			if($item['showfor']) {
				if($item['showfor'] == 'export' && !$isexport) continue;
				if($item['showfor'] == 'page' && $isexport) continue;
			}
			$width = $item['width'];
			if($isphone && $item['oneline']) $width = 999;
			$titles[] = array($width, $item['title']);
			
			$title_widths[$title_widths_pos][] = count($titles)-1;
			$title_widths_nowsize += intval($width);

			$nextOneline = false;
			for($ii = $key+1; $ii < count($listtitles); $ii++) {
				$item2 = $listtitles[$ii];
				if($item2['hidden']) continue;
				if($item2['showfor']) {
					if($item2['showfor'] == 'export' && !$isexport) continue;
					if($item2['showfor'] == 'page' && $isexport) continue;
				}
				if($item2['oneline']) {
					$nextOneline = true;
				}
				break;
			}

			if($item['oneline'] || $item['nextline'] || $title_widths_nowsize >= 360 || $nextOneline) {
				$title_widths_pos++;
				$title_widths_nowsize = 0;
			}
		}

		$tpl_name = "list.tpl.php";
		if($config_tpl_dir && is_file($config_tpl_dir."/".$tpl_name)) include($config_tpl_dir."/".$tpl_name);
		else include ADMIN_INC_ROOT."/tpl/".$tpl_name;

		$html = ob_get_clean();
		header("Content-Type: text/html;charset=utf-8");
		$data = array('html' => $html);
		echoRs(1, 'ok', $data);
	}
	exit;
}
if($act == 'downxlsx') {
	$fn_o = g("fn");
	if(strstr($fn_o, "..") || strstr($fn_o, "./")) exit;

	if(strstr($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger')) {
		gredirect("xls/".$fn_o);
		exit;
	}

	$exportname = g("exportname");
	if(!$exportname) $exportname = '导出数据';
	if(!$fn_o) exit;
	if(strpos($fn_o, 'xls/') === 0) $fn = $fn_o;
	else $fn = "xls/".$fn_o;
	$fn = str_replace(".xlsx", "", $fn) . ".xlsx";
	if(!is_file($fn)) exit;

	$r = gdownload($fn, $exportname);
	@unlink($fn);
	exit;
}

if($act == 'show') {
	admininc_check_token();
	$showtype = r('showtype');
	$config = $config_page[$showtype];
	
	if(!$config) exit;

	header("Content-Type: text/html; charset=utf-8");
	$id = intval(p('id'));
	$edit_id = $id;
	$extraJs = '';
	if($config['edit_extraJs']) $extraJs = $config['edit_extraJs'];

	$table = $config['table'];
	$editable = $config['editable'];
	$editable_func = $config['editable_func'];
	$data_info_func = $config['data_info_func'];
	$row_deal_func = $config['row_deal_func'];
	$data = array();
	
	if($data_info_func) {
		$data = $data_info_func(p('id'));
	} else {
		if($id != 0) {
			$sql = "select * from {$table} where id = ".$id;
			if($config['delmode'] == 1 && r('optype') != 2) $sql .= " and isdel=0";
			$data = fetchOne($sql);
			if(!$data) exit;
			if($row_deal_func) $data = $row_deal_func($data);
		}
	}
	$edit_data = $data;
	if($editable_func) {
		$editable = $editable_func($editable, $data);
	}
	if(p('id').'' === '') {
		if($editable) {
			foreach($editable as $key => $item) {
				if($item['notedit']) unset($editable[$key]);
			}
		}
	}
	
	if(r('m') == 'save') {
		if($id == 0) {
			if(!$config['addbt']) exit;
		} else {
			if($config['can_edit_func']) {
				$can_edit_func = $config['can_edit_func'];
				if(!$can_edit_func($id)) {
					exit;
				}
			}
		}
		$extraJs = '';
		save_editable($table, $id, $editable, $data);
		$rs['extraJs'] = $extraJs;
		echoRs(1, trim($saveTip), $rs);
		exit;
	}

	if($config['showdel']) {
		if(r('m') == 'del') {
			if($config['can_edit_func']) {
				$can_edit_func = $config['can_edit_func'];
				if(!$can_edit_func($id)) {
					exit;
				}
			}
			if($config['delmode'] == 1) {
				if(r('optype') == 2) query("update {$table} set isdel=0 where id=".$id);
				else query("update {$table} set isdel=1 where id=".$id);
			}
			else query("delete from {$table} where id=".$id);
			if($config['afterdel']) {
				$func = $config['afterdel'];
				$param = $config['delFuncParam'];
				if($param) $func($id, $param);
				else $func($id);
			}
			echoRs(1, 'ok');
		}
	}

	if($config['info_m']) {
		foreach($config['info_m'] as $key => $func) {
			if(r('m') == $key) {
				$func($id);
				exit;
			}
		}
	}
	
	$html = get_edit_html($showtype, $editable, $config, $data, $edit_id, $isphone);
	header("Content-Type: text/html;charset=utf-8");

	$rs = array('html' => $html);
	$rs['edit_id'] = $edit_id;
	if($edit_id > 0 && $data) $rs['edit_data'] = $data;
	$rs['editable'] = $editable;
	$rs['extraJs'] = $extraJs;
	if($config['edit_m']) $rs['edit_m'] = $config['edit_m'];
	echoRs(1, 'ok', $rs);
	exit;
}

if($act == 'downtpl') {
	admininc_check_token();
	$showtype = r('showtype');
	$config = $config_page[$showtype];
	
	if(!$config['editable'] || !$config['importname']) exit;
	$import_cover = $config['import_cover'];
	$table = $config['table'];

	$editable = $config['editable'];
	$importname = $config['importname'];
	$importtpl = $config['importtpl'];
	if($importtpl) {
		gredirect($importtpl);
		exit;
	}
	$titles = array();
	$zds = array();
	$widths = array();
	foreach($editable as $zd => $item) {
		$type = $item['type'];
		if($type != 'text' && $type != 'select' && $type != 'textarea' && $type != 'date') continue;
		if($item['notedit'] || strpos($zd, 'subtitle_') === 0) continue;
		$titles[] = $item['title'];
		$zds[] = $zd;
		$widths[] = 20;
	}

	if(!is_dir("tmp")) @mkdir("tmp");
	$fn = "tmp/".md5(microtime()."_".rand()).".xlsx";

	$list = array();
	if($import_cover) {
		$data = fetchAll("select * from `{$table}` limit 5000");
		
		foreach($data as $item) {
			$info = array();
			foreach($zds as $zd) {
				$info[] = $item[$zd];
			}
			$list[] = $info;
		}
		
	}
	$sheets = array(array(
		'titles' => $titles,
		'widths' => $widths,
		'list' => $list,
		'sheet_name' => 'Sheet1',
		'all_text' => '1',
	));
	getXlsx($sheets, $fn, false);

	gdownload($fn, $importname);
	@unlink($fn);
	exit;
}

if($act == 'import') {
	admininc_check_token();
	$showtype = r('showtype');
	$config = $config_page[$showtype];
	$formname = trim(r('formname'));
	$fkey = trim(r('fkey'));

	$isconfirm = false;
	if($fkey) {
		$isconfirm = true;
	}
	
	if(!$config['editable'] || !$config['importname']) exit;
	$editable = $config['editable'];
	$table = $config['table'];
	$import_cover = $config['import_cover'];


	function echoImportRs($msg, $suc = 0) {
		global $formname;
		echo '<script>window.parent.importFinish(decodeURIComponent("'.rawurlencode($msg).'"), '.$suc.', "'.$formname.'");</script>';
		exit;
	}

	set_time_limit(300);
	if($isconfirm || ($formname && $_FILES['file'] && $_FILES['file']['size'] > 0)) {
		if(!$isconfirm) {
			$fn = $_FILES['file']['name'];
			$fpath = $_FILES['file']['tmp_name'];
			$fsize = $_FILES['file']['size'];
			
			$a = explode(".", $fn);
			if(count($a) < 2) {
				echoImportRs("上传失败1！");
			}
			$ext = strtolower($a[count($a) - 1]);
			if($ext != 'xls' && $ext != 'xlsx') {
				echoImportRs("上传失败2！");
			}
			if(!is_dir("tmp")) @mkdir("tmp");
			$d = date("Ymd");
			
			$fkey = ukey().".".$ext;
			$path = "tmp/".$fkey;
			copy($fpath, $path);
		} else {
			$path = "tmp/".$fkey;
			$fsize = filesize($path);
		}
		if(file_exists($path) && filesize($path) == $fsize) {
			$a = readexcel($path);
			if(count($a) <= 1) {
				echoImportRs("文件中没有需要导入的内容！");
			}
			$titleInfo = array();
			$has1 = array();
			foreach($a[0] as $n1 => $title1) {
				$titleInfo[$title1] = $n1;
				$has1[$title1]++;
			}
			foreach($has1 as $title1 => $count1) {
				if($count1 > 1) {
					echoImportRs("Excel标题“{$title1}”有{$count1}列，请检查！");
				}
			}

			$preList = array();
			$sqllist = array();
			$insert_ids = array();
			for($i = 1; $i < count($a); $i++) {
				$row = $a[$i];

				$checks = trim(implode(" ", $row));
				if($checks == '') continue;
				

				$valueInfo = array();
				$n = -1;
				foreach($editable as $name => $item) {
					$type = $item['type'];
					$title = $item['title'];
					if($type != 'text' && $type != 'select' && $type != 'textarea' && $type != 'date') continue;
					if($item['notedit'] || strpos($name, 'subtitle_') === 0) continue;

					//if(!isset($titleInfo[$title])) {
					//	echoImportRs("模板中缺少列“".$title."”，请重新下载导入模板！");
					//}
					$n++;
					if(isset($titleInfo[$title])) {
						$n1 = $titleInfo[$title];
					} else {
						$n1 = $n;
					}
					

					$v = trim($row[$n1]);
					$valueInfo[$name] = $v;
				}
	
				$info = array();
				$zdList = array();
				$n = -1;
				foreach($editable as $name => $item) {
					$type = $item['type'];
					$title = $item['title'];
					if($type != 'text' && $type != 'select' && $type != 'textarea' && $type != 'date') continue;
					if($item['notedit'] || strpos($name, 'subtitle_') === 0) continue;
					
					$n++;
					if(isset($titleInfo[$title])) {
						$n1 = $titleInfo[$title];
					} else {
						$n1 = $n;
					}

					$v = trim($row[$n1]);
					if($item['must'] == '1' && $v == '' && !$item['notcheck']) {
						echoImportRs("第{$i}行的“{$title}”列未填写！");
					}
					if($v != '' && $item['reg']) {

						if(!save_checkReg($item['reg'], $v, $rs)) {
							echoImportRs("第{$i}行的“{$title}”列“{$v}”格式不正确！".($rs?($rs."！"):""));
						}
					}

					if($v != '' && $item['unique']) {
						$crow = fetchOne("select * from {$table} where `{$name}`='{$v}'");
						if($crow) {
							echoImportRs("第{$i}行的“{$title}”列已存在！");
						}
					}
					if($type == 'select') {
						$select = $item['select'];
						$parent_select = $item['parent_select'];
						if($parent_select) {
							list($name1, $link_select) = $parent_select;
							$v1 = $valueInfo[$name1];

							foreach($select as $key1 => $v2) {
								if($v1 == $v2) {
									$v1 = $key1;
									break;
								}
							}

							$select = $link_select[$v1];
						}
						if($select[$v]) {
						
						} else if(in_array($v, $select)) {
							foreach($select as $key1 => $v1) {
								if($v == $v1) {
									$v = $key1;
									break;
								}
							}
						} else {
							echoImportRs("第{$i}行的“{$title}”: “{$v}” 不属于可选值！");
						}
					}
					if(isset($item['default']) && trim($v) === '') $v = $item['default'];
					$info[$name] = $v;
					if(!$item['notauto']) $zdList[] = $name;
				}
				if(!$isconfirm) {
					$preList[] = $info;
					continue;
				}
				$update_id = 0;

				if($config['savecheck']) {
					$savecheck = $config['savecheck'];
					$rs = $savecheck(0, $info, $i, $editable);
					if(is_array($rs)) {
						if($rs['continue']) {
							continue;
						}
						if($rs['update_id']) {
							$update_id = $rs['update_id'];
						}
						if($rs['update_list']) {
							foreach($rs['update_list'] as $k1 => $v1) {
								if(!in_array($k1, $zdList)) $zdList[] = $k1;
								$info[$k1] = $v1;
							}
						}
					}
				}
				$sqlext = '';
				foreach($zdList as $zd) {
					if($sqlext != '') $sqlext .= ", ";
					$sqlext .= "`".$zd."`" ." = '".addslashes($info[$zd])."' ";
				}
				if($config['editaddsql']) {
					foreach($config['editaddsql'] as $key => $item) {
						$sqlext .= "," . $key ." = '".$item."' ";
					}
				}
				if($config['addsql'] && $update_id == 0) {
					foreach($config['addsql'] as $key => $item) {
						if(strpos($item, 'rand,') === 0) {
							$len = intval(substr($item, 5));
							$rand = substr(md5(time()."_".rand()), 0, $len);
							$sqlext .= "," . $key ." = '".$rand."' ";
						} else {
							$sqlext .= "," . $key ." = '".$item."' ";
						}
					}
				}
				if($update_id != 0) {
					$sql = "update {$table} set {$sqlext} where id={$update_id}";
					$insert_ids[] = $update_id;
				} else {
					$sql = "insert into {$table} set {$sqlext}";
					if(!$config['noaddtime']) $sql .= ",addtime=now()";
				}
				$sqllist[] = $sql;
			}

			if(!$isconfirm) {
				$listtitles = $config['listtitles'];
				$showListArr = array();
				$titles = array();
				$titles[] = array(60, '行');
				$totalwidth = 60;
				//pe1($preList);
				foreach($preList as $n => $item) {
					$lineArr = array();
					$lineArr[] = ($n+1).'';
					foreach($listtitles as $key => $titem) {
						if($titem['hidden'] || $titem['op'] || !isset($item[$titem['zd']])) continue;
						$lineArr[] = get_list_line_value($item, $titem);
						if($n == 0) {
							$totalwidth += $titem['width'];
							$titles[] = array($titem['width'], $titem['title']);
						}
					}
					
					$showListArr[] = $lineArr;
				}
				$isphone = false;
				$config['showpage'] = '';

				ob_start();
				include ADMIN_INC_ROOT."/tpl/list.tpl.php";
				$html = ob_get_clean();

				echoImportRs($fkey."#".$totalwidth."#".$html, 1);
			}
			
			$affrows = 0;
			if($import_cover) {
				
				$row1 = fetchOne("show create table {$table}");
		
				$csql = $row1['Create Table'];
				$csql = preg_replace("/ AUTO_INCREMENT=\d+/", "", $csql);


				$csql = replace_first($table, "{$table}_tmp", $csql);
				query("drop table {$table}_tmp", false);
				query($csql, false);
				query("begin");
				foreach($sqllist as $n => $sql) {
					$sql = replace_first($table, "{$table}_tmp", $sql);
					query($sql, false);
					if(stripos(trim($sql), 'insert') === 0 && afrows() != 1) {
						query("rollback");
						query("drop table {$table}_tmp", false);
						echoRs(0, "第".($n+1)."行数据格式错误！".$sql);
					}
					$affrows += 1;
					if(substr($sql, 0, 6) == 'insert') $insert_ids[] = insert_id();
				}
				query("commit");
				query("drop table {$table}");
				query("rename table {$table}_tmp to {$table}");
			} else {
				query("begin");
				$affrows = 0;
				foreach($sqllist as $n => $sql) {
					query($sql, false);
					if(stripos(trim($sql), 'insert') === 0 && afrows() != 1) {
						query("rollback");
						echoRs(0, "第".($n+1)."行数据格式错误！");
					}
					$affrows += 1;
					if(substr($sql, 0, 6) == 'insert') $insert_ids[] = insert_id();
				}

				query("commit");
				if($config['aftersave']) {
					$func = $config['aftersave'];
					$param = $config['saveFuncParam'];
					foreach($insert_ids as $insert_id) {
						if($param) $func($insert_id, $param);
						else $func($insert_id);
					}
				}
			}
			echoRs(1, "成功导入{$affrows}条记录！");

		} else {
			echoImportRs("上传失败3！");
		}
	} else {
		echoImportRs("上传失败4！");
	}
	exit;
}

if($act == 'umeditor') {
	admininc_check_token(2);
	$html = p("html");
	include(ADMIN_INC_ROOT."/include/umeditor/index.php");
	exit;
}

if($act == 'newifr') {
	$height = max(rn("height"), 300) - 50;
	$in_ifr = 1;
}

$tpl_name = "frame".($isphone?"_m":"").".tpl.php";
if($config_tpl_dir && is_file($config_tpl_dir."/".$tpl_name)) include($config_tpl_dir."/".$tpl_name);
else include ADMIN_INC_ROOT."/tpl/".$tpl_name;